// mobile bind
// ============

define(['zepto', 'utils', 'wxpay', 'sui'], function($, utils, wxpay){
  return {
    init: function(data) {
      if(data.jsConfig) {
        utils.configWeixin(data.jsConfig, false);
      }
      this.token = null;
      this.needpay = data.needpay;
      this.bindPay(data.order, data.agentMobile)
      this.initPage()
      this.initModal(data.pickupLocationId, data.returnLocationId)
      this.initCouponPicker(data.order,data.coupons)
    },
    
    initPage: function() {
      $('.offline-pay').click(function() {
        $.toast("线下支付成功，请联系负责销售进行线下支付！")
        setTimeout(function() {
              window.location.href = window.__CTX__.root + "/orders?status=UNPAID"
         }, 2000)
      })
    },
    
    initModal: function(pickupLocationId, returnLocationId) {
        var that = this;
        $.ajax({
          type: "GET",
          url: window.__CTX__.root + "/locations/"+pickupLocationId+"/working-hours",
          dataType: "json",
          success: function(data) {
            if(data.code == 0) {
               console.log("s",data.data)
                var pickupWorkHtml = ""
                $.each(data.data.workingHours, function(index, item){
                  pickupWorkHtml+= '<p style="margin: .25rem 0;"><span style="font-weight: bold;">'+ index +'</span>： ' + item + '</p>'
                });
                that.pickupWorkHtml = pickupWorkHtml
            } else {
              $.toast(data.message);
            }
          },
          error: function() {
            $.toast("查询失败");
          }
        })
        
        $.ajax({
          type: "GET",
          url: window.__CTX__.root + "/locations/"+returnLocationId+"/working-hours",
          dataType: "json",
          success: function(data) {
            if(data.code == 0) {
              console.log("d",data.data)
                var returnLocationId = ""
                $.each(data.data.workingHours, function(index, item){
                  returnLocationId+= '<p style="margin: .25rem 0;"><span style="font-weight: bold;">'+ index +'</span>： ' + item + '</p>'
                });
                
                that.returnLocationId = returnLocationId;
            } else {
              $.toast(data.message);
            }
          },
          error: function() {
            $.toast("查询失败");
          }
        })
        
      $(document).on('click','.icon-layout .iconfont', function (e) {
          $.modal({
              title:  '营业时间',
              text: '<div class="business-hours">'+
            ($(e.currentTarget).data("work") == "pickupLocation" ? that.pickupWorkHtml : that.returnLocationId)
                    +'</div>',
              buttons: [
                {
                  text: '<span style="color: #5d5c5c;">关闭</span>',
                },
              ],
              extraClass: 'business-hours-modal'
            })
        });
          
          $(document).on('click', '.modal-overlay', function() {
            $.closeModal('.modal');
          })
    },
    
    initCouponPicker: function(orderId, value) {
      var that = this;
      var couponsVal = ['不使用优惠券']
      var couponsCode = ['0']
      for(var i in value) {
        couponsVal.push(value[i].template_name)
        couponsCode.push(value[i].id)
      }
      
      $(".couponPicker").picker({
          toolbarTemplate: '<header class="bar bar-nav">\
          <button class="button button-link pull-right close-picker">确定</button>\
          <h1 class="title">优惠券</h1>\
          </header>',
          cols: [{
                  textAlign: 'center',
                  values: couponsCode,
                  displayValues: couponsVal
             }],
             onClose: function(picker) {
                 var oldPrice = $(".o-price .number").html()
              $.post(window.__CTX__.root + '/shopping/bind', {
                 'orderId': orderId,
                 'couponId': picker.value[0]
             }).done(function(response) {
                 utils.processResult(response, function(result) {
                    $.hidePreloader()
                    if(parseInt(picker.value[0]) == 0) {
                      $(".coupon-result").show().find('.price').empty().html($(".o-price .number").html())
                      $(".wechat-button").removeClass("hide")
                      $("#other-pay").addClass("hide")
                    } else {
                      for(var i in value) {
                   if(value[i].id == picker.value[0]) {
                     var price =  oldPrice - value[i].amount/100
                       console.log('jin',price.toFixed(2))
                       if(price > 0) {
//                       $(".wechat-button").removeClass("hide")
                         that.needpay = "true"
                       $(".coupon-result").show().find('.price').empty().html(price.toFixed(2))
//                       $("#other-pay").addClass("hide")
                       } else {
                         that.needpay = "false"
//                       $(".wechat-button").addClass('hide')
                       $(".coupon-result").show().find('.price').empty().html('0.00') 
//                       $("#other-pay").removeClass("hide")
                       }
                   } 
                  }
                    }
                 }, function(result) {
                    $.hidePreloader()
                    $.toast(result.message || '绑定优惠券失败')
                    setTimeout(function() {
                      window.location.reload();
                    }, 1000);
                })
            }).fail(function() {
                $.hidePreloader()
                $.toast('绑定优惠券失败')
                
            })
             },
             formatValue: function(picker, value, displayValue) {
                  $(this.input).next().val(value);
                  return displayValue;
             }
      });
    },

    /**
     * Bind mobile binding page event
     */
    bindPay: function(order, agentMobile) {
      var that = this;
      $(document).on('click', '.pay-button', function(e) {
        var $el = $(this)
        e.preventDefault();
        var submitingStatus = $(this).data("submiting");
        if(that.needpay && that.needpay == 'true') {
          // 开始执行支付逻辑
            $($el).data("submiting", "true");
            var type = e.currentTarget.dataset.type;
            var submiting = that.requestPayConfig(order, type)
            $.when(submiting).done(function(data, order) {
                //that.configWxPay(data, order, agentMobile)
                // TODO 跳转到支付页面
                window.location.href=data.paypage
            })
        } else {          // 优惠券直接抵扣，无需支付
          $.confirm('使用该优惠券将无需支付另外费用，是否确认下单？', function () {
            var submitingStatus = $(this).data("submiting");
              $($el).data("submiting", "true");
              var submiting = that.requestOtherPayConfig(order)
              $.when(submiting).done(function(data, order) {
                  window.location.href= window.__CTX__.root + "/shopping/result-success?orderId=" + order;
              })
          })
        }
      })
    },
    
//    /**
//     * Handle success WeChat pay, config WeChat JS SDK and invoke pay
//     */
//    configWxPay: function(data, order, agentMobile) {
//      var that = this;
//      wxpay.injectConfig(data.jsConfig, ['chooseWXPay'])
//      wxpay.invokePay(data.payConfig, function(res) {
//        
//        that.requestOrderMessage(agentMobile, order, function(data){},function(){});
//        setTimeout(function() {
//            window.location.href= window.__CTX__.root + "/shopping/result-success?orderId=" + order;
//        }, 1000)
//      })
//    },
//    
    requestPayConfig: function(order, type) {
      var that = this, defer = $.Deferred()
      $.post(window.__CTX__.root + '/shopping/pay', {
        'order': order,
        'type': type,
        'currentUrl': window.location.href
       }).done(function(response) {
          utils.processResult(response, function(result) {
            $.hidePreloader()
            defer.resolve(result.data, order)
          }, function(result) {
            $.hidePreloader()
            $.toast(result.message || '请求支付数据失败')
            setTimeout(function() {
              window.location.reload();
            }, 1000);
          })
        })
        
      return defer.promise()
    },
    
    requestOtherPayConfig: function(order) {
        var that = this, defer = $.Deferred()
        $.post(window.__CTX__.root + '/shopping/otherPay', {
          'order': order,
          'currentUrl': window.location.href
         }).done(function(response) {
            utils.processResult(response, function(result) {
              $.hidePreloader()
              defer.resolve(result.data, order)
            }, function(result) {
              $.hidePreloader()
              $.toast(result.message || '请求支付数据失败')
              setTimeout(function() {
                window.location.reload();
              }, 1000);
            })
          })
          
        return defer.promise()
      },
    
    /**
     * Request server to send order message to mobile
     */
    requestOrderMessage: function(mobile, orderId, success, failure) {
      $.showIndicator()
      utils.requestOrderMessage(mobile, orderId, function(result) {
        $.hideIndicator()
        success && success(result.data)
      }, failure)
    }
    
  }

})